var app = app || {};
app.winOpen = (function() {
	var wins = {};
	return function(url, winId, params) {
		if (winId && wins[winId] && wins[winId].closed !== true) {
			wins[winId].focus();
		}
		var params = params || {};
		var cfg = [
			'width='  + (params.width  || 720),
			'height=' + (params.height || 600),
			'top='    + (params.top    || 200),
			'left='   + (params.left   || 200),
		].join(',');

		var win = window.open(url, '', cfg);
		if (winId) {
			wins[winId] = win;
		}
	}
})();


(function() {
	'use strict';
	/**
	 * =================================================
	 *  
	 *     公共辅助模块
	 * 
	 * =================================================
	 */
	angular.module('Common', [])
		.config(['$httpProvider',function($httpProvider) {
			// ==== 改写$http请求方式 ==============
			$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
			var param = function(obj) {
			  var query = '',
			    name, value, fullSubName, subName, subValue, innerObj, i;

			  for (name in obj) {
			    value = obj[name];

			    if (value instanceof Array) {
			      for (i = 0; i < value.length; ++i) {
			        subValue = value[i];
			        fullSubName = name + '[' + i + ']';
			        innerObj = {};
			        innerObj[fullSubName] = subValue;
			        query += param(innerObj) + '&';
			      }
			    } else if (value instanceof Object) {
			      for (subName in value) {
			        subValue = value[subName];
			        fullSubName = name + '[' + subName + ']';
			        innerObj = {};
			        innerObj[fullSubName] = subValue;
			        query += param(innerObj) + '&';
			      }
			    } else if (value !== undefined && value !== null)
			      query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
			  }

			  return query.length ? query.substr(0, query.length - 1) : query;
			};

			// Override $http service's default transformRequest
			$httpProvider.defaults.transformRequest = [function(data) {
			  return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
			}];
			// ==== END 改写$http请求方式 ==============
		}])
		.factory('CFG', ['$rootScope', function($rootScope) {
			var config = window.app && window.app.config || {};
			config.baseUrl = '/';
			config.adminDir = '/hs_mng/';
			config.getTplUrl = function(id) {
				return '/houtai/tpl/' + id + '.html';
			};
			return config;
		}])
		.factory('API', ['$http', '$q', function($http, $q) {
			function fetch(url, params, method) {
				var defer = $q.defer();
				params.debug = 'yx4007';
				$http({
					url : url,
					data : params || {},
					method : method || 'post',
					cache : false,
				}).success(function(response) {
					try {
						if( typeof response === 'object' ){
							
						}else{
							try {
								var response = JSON.parse(response);
							} catch (e) {
								throw "Response Type Error:Not JSON";
							};
						}
						
						if (response.error === undefined) {
							throw "Response Format Error";
						};
						if (response.error !== 0) {
							var msg = response.msg || '服务器错误,请稍后再试!';
							alert(msg);
							throw "SERVER ERROR";
						};
						defer.resolve(response);
					} catch (e) {
						console.trace('API.fetch.done.error', {
							error: e,
							response: response
						});
						defer.reject(response);
					};
				}).error(function(response, msg) {
					console.trace('API.fetch.fail.error', arguments);
					var msg = '网络错误';
					alert(msg);
					defer.reject(response);
				});
				return defer.promise;
			}
			return {
				fetch: function(url, params, method) {
					return fetch(url,params,method);
				},
				post: function(url, params) {
					return fetch(url, params, 'POST');
				},
				get: function(url, params) {
					return fetch(url, params, 'GET');
				},
				http:function(config){
					return $http(config);
				}
			};
		}])
		/** 分页指令
		 * 	<pagins 
		 *		total-rows="totalRows" 
		 *		curr-page="params.page" 
		 *		pagesize="params.pagesize"
		 *		count="10"
		 *		on-choose-page="choosePage(page)"
		 *		on-choose-pagesize="choosePagesize(pagesize)"
		 *	></pagins>
		 */
		.directive('pagins', ['$rootScope', 'CFG', function($rootScope, cfg) {
			return {
				scope: {
					totalRows: '=', //总行数
					currPage: '=', //当前页码
					pagesize: '=', //每页显示条数
					count: '@', //显示页码个数
					onChoosePage: '&',
					onChoosePagesize: '&',
				},
				restrict: 'AE',
				templateUrl: cfg.getTplUrl('pagins'),
				replace: true,
				link: function($scope, iElm, iAttrs, controller) {
						$scope.pageCount = 0; //总页数
						$scope.page = $scope.page || 1;
						$scope.pagesize = $scope.pagesize || 20;
						// 重新计算总页数
						function resetPageCount() {
							$scope.pageCount = Math.ceil($scope.totalRows / $scope.pagesize);
						};
						// 重新计算页码列表
						function resetPagins() {
							var count = parseInt($scope.count) || 10; //显示10个页码
							var min = $scope.currPage - 5;
							min = min >= 1 ? min : 1;
							var max = min + count - 1;
							max = max >= $scope.pageCount ? $scope.pageCount : max;
							var list = [];
							for (var i = min; i <= max; i++) {
								list.push(i);
							};
							$scope.list = list;
						}
						// 获取页码class
						$scope.getPaginClass = function(page) {
							return $scope.currPage == page ? 'current' : '';
						};

						$scope.choosePage = function(page) {
							$scope.currPage = page;
							$scope.onChoosePage({
								page: page
							});
						};
						$scope.choosePagesize = function() {
							$scope.onChoosePagesize({
								pagesize: $scope.pagesize
							});
						};

						$scope.$watch('totalRows', function(n, o) {
							resetPageCount();
							resetPagins();
						});
						$scope.$watch('pagesize', function(n, o) {
							resetPageCount();
							resetPagins();
						});
						$scope.$watch('currPage', function(n, o) {
							resetPagins();
						});
					} //END link () ======================================
			}; // END return {} ======================================
		}]) // END directive(pagins) =================================
		/** 转为数字(用于select.option.value)
		 * conver-to-number
		 */
		.directive('convertToNumber', function() {
			return {
				require: 'ngModel',
				link: function(scope, element, attrs, ngModel) {
					ngModel.$parsers.push(function(val) {
						return parseInt(val, 10);
					});
					ngModel.$formatters.push(function(val) {
						return '' + val;
					});
				}
			};
		}) // END directive convertToNumber
		/** 字符串转数字 用于input[type="number"]
		 * string-to-number
		 */
		.directive('stringToNumber', function() {
			return {
				require: 'ngModel',
				link: function(scope, element, attrs, ngModel) {
					ngModel.$parsers.push(function(value) {
						return '' + value;
					});
					ngModel.$formatters.push(function(value) {
						return parseFloat(value);
					});
				}
			};
		}) // END directive stringToNumber
		/** "加载中"遮罩层服务
		 */
		.factory('Loading', ['$document', '$window', function($document, $window) {
			var elLoading = document.createElement('DIV');
			document.body.appendChild(elLoading);
			var elContent = document.createElement('DIV');
			elLoading.appendChild(elContent);

			elLoading = angular.element(elLoading);
			elContent = angular.element(elContent);

			elLoading.css({
				display: 'none',
				position: 'absolute',
				top: 0,
				left: 0,
				right: 0,
				bottom: 0,
				width: '100%',
				height: document.body.scrollHeight + 'px',
				background: '#000',
				opacity: 0.5,
				color: '#fff',
				textAlign: 'center',
				verticalAlign: 'middle',
				zIndex: 99998,
			});
			elContent.text('加载中...').css({
				fontSize: '22px',
			})
			return {
				show: function(content) {
					if (content) {
						elContent.html(content);
					};
					elLoading.css({
						display: 'block',
						height: (document.body.scrollTop + document.body.scrollHeight) + 'px',
					});
					elContent.css({
						marginTop: document.body.scrollTop + window.screen.availHeight / 3 + 'px',
					});
				},
				hide: function() {
					elLoading.hide();
				},
			}
		}]) // END service Loading
		/** 数据表格指令
				<table-list
					list="="
					total-rows="="
					on-params-change="function(params)"
				></table-list>
		 */
		.directive('tableList', ['CFG', function(CFG) {
			return {
				scope: {
					list: '=',
					totalRows: '=',
					onParamsChange: '&',
					caption: '=?',
					thItems: '=?',
					tdClass: '=?',
					showPagins: '=?',
					currPage: '=?',
					pagesize: '=?',
					paginCount: '=?',
				},
				restrict: 'AE',
				templateUrl: CFG.getTplUrl('table'),
				replace: true,
				link: function($scope, iElm, iAttrs, controller) {
						var config = CFG.tableList || {};
						// 参数集合
						var params;
						$scope.params = params = {
							order: null,
							sort: 0,
							page: $scope.currPage || 1,
							pagesize: $scope.pagesize || 20,
						};

						function paramsChange() {
							$scope.onParamsChange({
								params: params
							});
						}
						// thead =======================
						var thItems = $scope.thItems || config.thItems || [];
						if (angular.isArray(thItems)) {
							for (var i = 0; i < thItems.length; i++) {
								if (angular.isString(thItems[i])) {
									thItems[i] = {
										text: thItems[i],
									}
								}
							}
						} else {
							thItems = [];
						}
						$scope.thItems = thItems;
						// ==== 排序
						var orders = {};
						var sort = 0;
						$scope.sort = function(order) {
							orders[order] = !orders[order];
							params.sort = Number(orders[order]);
							params.order = order;
							params.page = 1;
							paramsChange();
						};
						// END thead ====================
						// tbody ========================
						// ==== 获取tdClass
						var tdClass = $scope.tdClass || config.tdClass || {};
						$scope.getTdClass = function(tdIndex) {
							return tdClass[tdIndex] || '';
						};
						// ==== 监听数据列表list改变
						$scope.$watch('list', function() {
							if (!$scope.list) {
								return true;
							}
							bindClickUsername();
						});

						// END tbody ========================
						// pagins =======================
						$scope.showPagins = $scope.showPagins === undefined ? true : $scope.showPagins;
						$scope.paginCount = $scope.paginCount || 10;
						$scope.choosePage = function(page) {
							params.page = page;
							paramsChange();
						};
						$scope.choosePagesize = function(pagesize) {
							params.page = 1;
							params.pagesize = pagesize;
							paramsChange();
						}
						$scope.$watch('currPage', function(o, n) {
							console.log('tablelist.watch.currpage', o, n);
							$scope.params.page = $scope.currPage;
						});
						// END pagins =======================


						function bindClickUsername() {
							var subWins = {};
							var promise = setInterval(function() {
								var $username = iElm.find('.username');
								console.log('directive.tableList.watch.list', $username);
								if (!$username.length) {
									return false;
								}
								clearInterval(promise);
								$username.css({
									cursor: 'pointer',
								}).on('click', function(e) {
									var $nickname = angular.element(e.target);
									var $tr = $nickname.parent();
									var $id = $tr.find('.userID');
									var id = parseInt($id.text());
									if (id <= 0 || isNaN(id)) {
										return false;
									}
									if (!subWins[id] || subWins[id].closed) {
										var url = '/hs_mng/user/detail?uid=' + id;
										subWins[id] = window.open(url, '', 'width=600,height=720,top=200,left=200,location=no');
									} else {
										subWins[id].focus();
									}
								});
							}, 100);
						} // END bindClickUsername()
					} // END link()
			}; // END return {}
		}]) // END directive.tableList
	; // END module Common ==============================================
	/*
	 * ========================================================================
	 * 
	 *     图表Chart模块
	 * 
	 * ======================================================================== 
	 */
	angular.module('Chart', [])
		.factory('ChartDelegate', ['$rootScope', function($rootScope) {
			var instances = {};
			window.app.instances = window.app.instances || {};
			window.app.instances.chart = instances;
			return {
				registerInstance: function(id, instance) {
					instances[id] = instance;
				},
				getInstanceById: function(id) {
					var id = id || 'default';
					if (!instances[id]) {
						instances[id] = {};
					}
					return instances[id];
				},
			}
		}])
		.directive('chart', ['ChartDelegate', function(ChartDelegate) {
			return {
				scope: {
					id: '@',
					width: '@',
					height: '@',
				},
				template: '<div></div>',
				replace: true,
				restrict: 'AE',
				link: function($scope, iElm, iAttrs, controller) {

					var id = $scope.id || 'default';
					var height = $scope.height || '500px';
					var width = $scope.width || '100%';

					var elChart = iElm[0];
					elChart.style.height = height;
					elChart.style.width = width;
					var chart = echarts.init(elChart);

					var openObj = {
						setOption: function(options) {
							console.log('directive.chart', options);
							chart.setOption(options);
						},
					}

					ChartDelegate.registerInstance(id, openObj);
				}
			};
		}]);
	/*
	 * ========================================================================
	 * 
	 *     荣钧饮水公共模块
	 * 
	 * ======================================================================== 
	 */
	angular.module('Ys', ['Common'])
		/**
		 * 学校模型
		 */
		.factory('School', ['$rootScope', '$http', 'CFG', function($rootScope, $http, CFG) {
			var list = CFG.schoolList || {};
			return {
				fetchSchoolList: function(async) {
					if (!list) {
						console.trace('schoolList is empty,CFG:',CFG);
						return [];
					} else {
						return list;
					}
				},
				getSchoolNameById: function(id) {
					return list[id] && list[id].name || '';
				},
				getSchoolById:function(id){
					return list[id] || {id:0,name:''};
				}
			}
		}])
})();